#include "control.h"
#include "define.h"
#include "game.h"

namespace gm
{
    char keyid;
    
    // -----按键对应的函数调用---------------------------------
    std::map<char, std::function<void()>> comm_func{
        {KEY_Q, command_quit},      /*退出*/
        {KEY_W, command_rotate},    /*旋转*/
        {KEY_A, command_left},      /*向左*/
        {KEY_D, command_right},     /*向右*/
        {KEY_S, command_down},      /*下降*/
        {KEY_BS, command_drop},     /*直降*/
        {KEY_R, command_hold},      /*Hold*/
        {KEY_H, command_help}       /*帮助*/
        //TODO: 增加新的调用

    };
    //--------------------------------------------------------

#ifdef __linux__
    char getch()
    {
        struct termios old,cur;
        tcgetattr(0,&cur);
        old=cur;
        cfmakeraw(&cur);
        tcsetattr(0,0,&cur);
        char c=getchar();
        tcsetattr(0,0,&old);
        return c;
    }
#endif

    char get_keyid()
    {
        return keyid;
    }

    void key_event()
    {
        while (running)
        {
            keyid=getch();
            auto c = comm_func[keyid];
            if(c!=NULL) c();
        }
    }

    void start_listener()
    {
        std::thread t(key_event);
        t.detach();
    }


    void command_quit()
    {
        quit();
    }
    void command_rotate()
    {
        rotate();
    }
    void command_left()
    {
        left();
    }
    void command_right()
    {
        right();
    }
    void command_down()
    {
        down();
    }

    void command_drop()
    {
        drop();
    }

    void command_hold()
    {
        hold();
    }

    void command_help()
    {
        help();
    }
}